import argparse

import win32clipboard as w
import win32con
import win32api
import win32gui
import time
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
import os
import requests
import sys
import ctypes
# import ntplib
import pyautogui

def move_to_top(name = 'SSTap Beta 1.0.9.7 - 享受游戏'):
    def get_all_hwnd(hwnd, mouse):
        if (win32gui.IsWindow(hwnd) and
                win32gui.IsWindowEnabled(hwnd) and
                win32gui.IsWindowVisible(hwnd)):
            hwnd_map.update({hwnd: win32gui.GetWindowText(hwnd)})

    hwnd_map = {}
    win32gui.EnumWindows(get_all_hwnd, 0)

    for h, t in hwnd_map.items():
        print(h, t)
        if t:
            if t == name:
                # h 为想要放到最前面的窗口句柄
                print(h)

                win32gui.BringWindowToTop(h)
                # shell = win32com.client.Dispatch("WScript.Shell")
                # shell.SendKeys('%')

                # 被其他窗口遮挡，调用后放到最前面
                win32gui.SetForegroundWindow(h)

                # 解决被最小化的情况
                win32gui.ShowWindow(h, win32con.SW_RESTORE)

                return h

# 把文字放入剪贴板
def setText(aString):
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
    w.CloseClipboard()


# 模拟ctrl+V
def ctrlV():
    win32api.keybd_event(17, 0, 0, 0)  # ctrl
    win32api.keybd_event(86, 0, 0, 0)  # V
    win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


# 模拟alt+s
def altS():
    win32api.keybd_event(18, 0, 0, 0)
    win32api.keybd_event(83, 0, 0, 0)
    win32api.keybd_event(83, 0, win32con.KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)


# 模拟enter
def enter():
    win32api.keybd_event(13, 0, 0, 0)
    win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0)


# 模拟单击
def click():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)


# 移动鼠标的位置
def movePos(x, y):
    win32api.SetCursorPos((x, y))
def log_string(log, string):
    # message = str(time.strftime("%Y-%m-%d %H:%M:%S.%f'", time.localtime()))+"  "+string
    message = str( datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]) + "  " + string
    log.write(message+ '\n')
    log.flush()
    print(message)

def create_path(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)


def is_admin():
    """判断当前用户是否是管理员"""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


def set_time():
    hosts = ['0.cn.pool.ntp.org', '1.cn.pool.ntp.org', '2.cn.pool.ntp.org', '3.cn.pool.ntp.org']
    t = ntplib.NTPClient()
    for host in hosts:
        try:
            res = t.request(host, port='ntp', version=4, timeout=5)
            if res:
                ts = res.tx_time
                # 方法一
                # _date = time.strftime('%Y-%m-%d', time.localtime(ts))
                # _time = time.strftime('%X', time.localtime(ts))
                _date, _time = str(datetime.datetime.fromtimestamp(ts))[:22].split(' ')

                if is_admin():
                    os.system('date {} && time {}'.format(_date, _time))
                    # 方法二
                    # tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(ts)
                    # win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0)
                else:
                    # 重新运行这个程序使用管理员权限
                    print("使用管理员权限运行该程序")
                    if sys.version_info[0] == 3:  # Python主要版本号（major）
                        ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
                print("服务器时间:", _date, _time)
                print("本地的时间:", datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
                return True
        except:
            print("set_time error")
            pass
def book_cmd(user="zfr"):
    # book_cmd_old(user)
    # import getState
    # if user=="zfr" and getState.get_heartbeat_state()==True:#zfr and 6400在线就不执行
    #     print("不执行")
    #     return
    # set_time()
    # while True:
    #     try:
    #         book_cmd_old(user)
    #         break
    #     except:
    #         print("error")
    #         pass
    book_cmd_old()
def genHtml(field="1号场地",startTime="09"):
    # day = "2024-08-09"  # 日期
    # time_id = "f3f7870a-a4d4-1e14-de22-21ba9a283ad11"  # 时间段
    # field_id = "ec640b11-140f-4377-2b56-3f6e011afec14"  # 场地
    if field not in["1号场地","2号场地","3号场地"]:
        print("场地选择错误")
    if field=="1号场地":
        field_id="ec640b11-140f-4377-2b56-3f6e011afec14"
    if field == "2号场地":
        field_id = "a008172d-b1ce-8af0-946d-6d8d11fa59f17"
    if field == "3号场地":
        field_id = "11d56035-9564-7470-8dcc-860cb06644c14"

    timeSuffix=str(int(startTime)-8)
    # timeSuffix =(2-len(timeSuffix))*"0"+timeSuffix

    time_id="f3f7870a-a4d4-1e14-de22-21ba9a283ad"+timeSuffix
    # 获取后天
    now = datetime.datetime.now()
    date_after = ((now + datetime.timedelta(days=2)).strftime("%Y-%m-%d"))
    day = date_after

    # today = datetime.datetime.today()
    # day_of_week = today.weekday()

    htmlUrl = "http://zky.sass.elstp.cn/make/Field/Badminton/?t=Reserve&field_id={}&day={}&time_id={}&type=afb16847-b58c-b294-1ec1-284c9f3bf931".format(
        field_id, day, time_id)
    # print(htmlUrl)
    return htmlUrl

def book_cmd_old(user="zfr"):
    today = str(time.strftime("%Y-%m-%d", time.localtime()))
    log_path = 'logs'
    create_path(log_path)
    log = open(log_path + "/{}_log.txt".format(today),"a")
    h = move_to_top("微信")


    # 没找到微信则打开微信
    if(h == None):
        try:
            exe_path = r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe"
            win32api.ShellExecute(0, 'open', exe_path, '', '', 1)
        except:
            exe_path = r"C:\Program Files\Tencent\WeChat\WeChat.exe"
            win32api.ShellExecute(0, 'open', exe_path, '', '', 1)

        time.sleep(1)
        move_to_top("微信")
    # print(h)


    # 获取鼠标当前位置
    # hwnd=win32gui.FindWindow("MozillaWindowClass",None)
    hwnd = win32gui.FindWindow("WeChatMainWndForPC", None)
    win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
    win32gui.MoveWindow(hwnd, 0, 0, 1000, 700, True)

    # 移动到聊天,防止出错后直接在通信录的搜索框
    movePos(28, 147)
    time.sleep(0.5)
    click()
    time.sleep(0.5)

    time.sleep(0.5)
    # 1.移动鼠标到通讯录位置，单击打开通讯录
    movePos(28, 147)
    time.sleep(0.5)
    click()
    time.sleep(0.5)
    # 2.移动鼠标到搜索框，单击，输入要搜索的名字
    movePos(148, 35)
    time.sleep(0.5)
    click()

    today = datetime.datetime.today()
    day_of_week = today.weekday()

    admin_name = "文件传输助手"
    text_msg0=""
    text_msg1 = ""
    # 周3
    # if day_of_week == (3 - 1):
    #     if user == "zfr":
    #         text_msg0 = genHtml("1号场地","19")
    #         # text_msg1 = genHtml("3号场地", "22")
    # elif day_of_week == (4 - 1):
    #     if user == "zfr":
    #         text_msg0 = genHtml("1号场地","16")
    #         text_msg1 = genHtml("1号场地", "17")
    #周五
    if day_of_week == (5 - 1):
        if user == "zfr":
            text_msg0 = genHtml("2号场地","16")
            text_msg1 = genHtml("2号场地", "17")

    else:

        text_msg0 = "只是日志0而已"



    log_string(log, admin_name)
    setText(admin_name)
    time.sleep(0.5)
    ctrlV()
    time.sleep(1)  # 别问我为什么要停1秒，问就是给微信一个反应的时间，他反应慢反应不过来，其他位置暂停的原因同样
    enter()
    time.sleep(1)
    # 3.复制要发送的消息，发送

    setText(text_msg0)
    log_string(log, text_msg0)
    ctrlV()
    time.sleep(1)
    altS()

    if text_msg0 == "只是日志0而已":
        return 1

    if text_msg1!="":
        time.sleep(1)
        setText(text_msg1)
        log_string(log, text_msg1)
        ctrlV()
        time.sleep(1)
        altS()

    wechatBrowserCloseX=1897
    wechatBrowserCloseY = 12
    firstLabelX=237
    firstLabelY = 13
    submitButtonX=966
    submitButtonY = 914
    ensureButtonX=1040
    ensureButtonY = 134
    secondLabelX = 460
    secondLabelY = 13
    # 靠近输入框的链接,并删除所有的窗口
    movePos(792, 414)
    time.sleep(0.5)
    click()
    time.sleep(0.5)
    movePos(wechatBrowserCloseX, wechatBrowserCloseY)
    time.sleep(0.5)
    click()
    time.sleep(0.5)


    # 靠近输入框的链接
    movePos(792, 414)
    time.sleep(0.5)
    click()
    time.sleep(0.5)

    #切换回去微信
    pyautogui.hotkey('alt', 'tab')
    # 倒数第二个链接
    if text_msg1 != "":
        movePos(792, 264)
        time.sleep(0.5)
        click()
        time.sleep(0.5)


    # 移动到第一个标签
    movePos(firstLabelX, firstLabelY)
    time.sleep(0.5)
    click()
    # 提交按钮
    movePos(submitButtonX, submitButtonY)
    time.sleep(0.5)
    click()
    # 确认预定
    movePos(ensureButtonX, ensureButtonY)
    time.sleep(0.5)

    cnt = 10
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    while True:

        response = requests.get("http://vv.video.qq.com/checktime?otype=json", headers=headers)
        flag = True
        if response.status_code == 200:
            text = response.text
            jsonContent = text[13:-1]
            # print(jsonContent)
            if text is not None:
                dict = eval(jsonContent)
                if "t" in dict:
                    flag = False
                    # print(dict)
                    now_time = datetime.datetime.fromtimestamp(dict["t"])
                    # print(now_time)
        if flag:
            now_time = datetime.datetime.now()
        cur_time = now_time.hour * 3600 + now_time.minute * 60 + now_time.second + now_time.microsecond / 1000000  # microsecond是微妙,转换为秒

        # log_string(log, str(now_time))
        # 等待时间00
        # 6500-M2,这个时间估计每台电脑都不一样?
        # if cur_time >= 8 * 3600 + 0*60 + bias_time:
        # bias_time = -1.5#七点59分 -1
        # if cur_time >= 17 * 3600 + 28 * 60 + 2:
        if cur_time >= 8 * 3600 + 0 * 60 + 2:
            # time.sleep(0.2)#休眠200MS，防止时间对不上
            now_time = datetime.datetime.now()
            log_string(log, "click " + str(now_time))
            # time.sleep(1)
            break
        else:
            time.sleep(0.1)
            if cnt>20:
                log_string(log, "waiting...")
                cnt=0
        # time.sleep(10)
        cnt+=1

    # # time.sleep(5)
    # time.sleep(0.2)
    # for i in range(5):
    #     time.sleep(0.2)
    #     click()

    if text_msg1 != "":
        # 移动到第2个标签
        movePos(secondLabelX, secondLabelY)
        time.sleep(0.2)
        click()
        # 提交按钮
        movePos(submitButtonX, submitButtonY)
        time.sleep(0.2)
        click()
        # 确认预定
        movePos(ensureButtonX, ensureButtonY)
        time.sleep(0.2)


        # for i in range(5):
        #     time.sleep(0.2)
        #     click()

    #成后就要退出，关闭
    movePos(wechatBrowserCloseX, wechatBrowserCloseY)
    time.sleep(0.5)
    click()
    time.sleep(0.5)


    return 1


# today = str(time.strftime("%Y-%m-%d", time.localtime()))
# log_path = 'logs'
# create_path(log_path)
# log = open(log_path + "/{}_log.txt".format(today),"a")
# while True:
#     time.sleep(0.01)
#     log_string(log, "waiting...")
# for i in range(10):
#     import pyautogui
#     pyautogui.hotkey('win', 'd')
#     time.sleep(5)
#     book_cmd_old()
#     time.sleep(5)

if __name__ == "__main__":

    code_version = 20240806
    print(os.getcwd())
    print("file name: %s" % (__file__), ", code Version: ", code_version)

    # time.sleep(10)
    # exit()
    parser = argparse.ArgumentParser()
    parser.add_argument('--user', default="zfr", type=str)
    args = parser.parse_args()

    scheduler = BlockingScheduler()
    # scheduler.add_job(func=book_cmd, args=(),
    #               trigger='cron', day_of_week=1 - 1, hour=7, minute=59, misfire_grace_time=60*5)  # 周1约周3
    scheduler.add_job(func=book_cmd, args=(args.user,),
                      trigger='cron', hour=7, minute=50, misfire_grace_time=60 * 5)
    scheduler.start()
    # book_cmd()